package cn.elead.chaos.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.elead.chaos.framework.properties.Security;
import cn.elead.chaos.shiro.jwt.JWTToken;
import cn.elead.chaos.sso.core.user.LoginUser;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtAuthFilter extends AuthenticatingFilter {

	private Security security;
	
	public JwtAuthFilter(Security security) {
		this.security = security;
	}

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) // 对于OPTION请求做拦截，不做token校验
			return false;

		return super.preHandle(request, response);
	}

	@Override
	protected void postHandle(ServletRequest request, ServletResponse response) {
		request.setAttribute("jwtShiroFilter.FILTERED", true);
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		if (this.isLoginRequest(request, response))
			return true;
		Boolean afterFiltered = (Boolean) (request.getAttribute("jwtShiroFilter.FILTERED"));
		if (BooleanUtils.isTrue(afterFiltered))
			return true;

		boolean allowed = false;
		try {
			allowed = executeLogin(request, response);
		} catch (IllegalStateException e) { // not found any token
			log.error("Not found any token");
		} catch (Exception e) {
			log.error("Error occurs when login", e);
		}
		return allowed || super.isPermissive(mappedValue);
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
		String jwtToken = getAuthzHeader(servletRequest);
		if (StringUtils.isNotBlank(jwtToken)) {
			return new JWTToken(jwtToken);
		}
		return null;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
		HttpServletResponse httpResponse = WebUtils.toHttp(servletResponse);
		httpResponse.setCharacterEncoding("UTF-8");
		httpResponse.setContentType("application/json;charset=UTF-8");
		httpResponse.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
		return false;
	}

	/**
	 * 认证成功
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		if (token instanceof JWTToken) {
			JWTToken jwtToken = (JWTToken) token;
			LoginUser user = (LoginUser) subject.getPrincipal();
			if(log.isDebugEnabled()) {
				log.debug("Shiro Login Success, user:{}, token:{}", user.getLoginName(), jwtToken.getToken());
			}
		}
		return true;
	}

	/**
	 * 认证成功
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		log.error("Validate token fail, token:{}, error:{}", token.toString(), e.getMessage());
		return false;
	}

	protected String getAuthzHeader(ServletRequest request) {
		HttpServletRequest httpRequest = WebUtils.toHttp(request);
		String authToken = "Authorization";
		// 判断是否配置了token
		if(ObjectUtil.isNotEmpty(security) && ObjectUtil.isNotEmpty(security.getToken())) {
			authToken = security.getToken();
		}
		String header = httpRequest.getHeader(authToken);
		return StringUtils.removeStart(header, "Bearer ");
	}

}
